import json
import mysql.connector
from datetime import datetime

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '040908',
    'database': 'wearable_data'
}

def connect_to_db():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        return conn
    except mysql.connector.Error as err:
        print(f"数据库连接错误: {err}")
        return None

def import_data(conn, data, scenario):
    cursor = conn.cursor()
    
    # 准备SQL语句 - 修改字段名以匹配数据库表结构
    sql = """
    INSERT INTO wearable_data 
    (heart_rate, timestamp, device_id, is_anomaly, anomaly_description) 
    VALUES (%s, %s, %s, %s, %s)
    """
    
    try:
        for record in data:
            # 转换时间戳
            timestamp = datetime.fromisoformat(record['timestamp'])
            
            # 准备数据
            values = (
                record['heartRate'],
                timestamp,
                f"device_{scenario}",  # 使用场景作为设备ID
                False,  # 默认不是异常
                None    # 默认没有异常描述
            )
            
            cursor.execute(sql, values)
        
        conn.commit()
        print(f"成功导入{len(data)}条{scenario}场景的数据")
        
    except mysql.connector.Error as err:
        print(f"导入数据时出错: {err}")
        conn.rollback()
    
    finally:
        cursor.close()

def main():
    # 连接数据库
    conn = connect_to_db()
    if not conn:
        return
    
    try:
        # 导入不同场景的数据
        scenarios = ['normal', 'exercise', 'sleep', 'stress']
        
        for scenario in scenarios:
            filename = f"test_data_{scenario}.json"
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    import_data(conn, data, scenario)
            except FileNotFoundError:
                print(f"找不到文件: {filename}")
            except json.JSONDecodeError:
                print(f"JSON解析错误: {filename}")
    
    finally:
        conn.close()

if __name__ == "__main__":
    main() 